﻿using System.IO;
using System.Security.AccessControl;

namespace AD域工具.Tool
{
    #region 文件夹权限管理
    /// <summary>
    /// 文件夹权限管理
    /// </summary>
    #endregion
    class FolderPermission
    {
        #region 为文件夹添加指定用户的权限
        /// <summary>
        /// 为文件夹添加指定用户的权限
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <param name="username">需要设置权限的用户</param>
        /// <param name="control">需要的权限</param>
        #endregion
        public static void AddFolderPermission(string dirPath, string username, FileSystemRights control)
        {
            //获取文件夹信息
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            //获得该文件夹的所有访问权限
            DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
            //设定文件ACL继承
            InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
            //设置用户的访问权限规则 完全控制权限
            FileSystemAccessRule everyoneFileSystemAccessRule = new FileSystemAccessRule(username, control, inherits, PropagationFlags.None, AccessControlType.Allow);
            dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out _);
            //设置访问权限
            dir.SetAccessControl(dirSecurity);
        }

        #region 为文件夹添加指定用户的所有权限
        /// <summary>
        /// 为文件夹添加指定用户的所有权限
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <param name="username">需要设置权限的用户</param>
        #endregion
        public static void AddFolderFullControl(string dirPath, string username)
        {
            FolderPermission.AddFolderPermission(dirPath, username, FileSystemRights.FullControl);
        }
    }
}
